#include "lvgl_isd_resource.h"
#include <stdlib.h>
#include <string.h>
#include "rtservice.h"


typedef struct _lvgl_res{
    rt_list_t list;
    char *name;
    int32_t id;
    int32_t room;
    void *dsc;
    unsigned char *data;
    int32_t size;
}LVGLResource ;

rt_list_t lvgl_resource_header;
int32_t lvgl_resource_id = 0;

void lvgl_isd_resource_init()
{
    rt_list_init(&lvgl_resource_header);
}

bool lvgl_isd_resource_exist(const char *name)
{
    LVGLResource *res;

    rt_list_for_each_entry(res, &lvgl_resource_header, list){
        if (strcmp(res->name, name) == 0) {
            return true;
        }
    }
    return false;
}

int32_t lvgl_isd_resource_add(const char *name, lv_img_dsc_t dsc, int32_t room)
{
    LVGLResource *res;
    lv_img_dsc_t *pdsc;

    res = (LVGLResource*)malloc(sizeof (LVGLResource));

    res->name = (char*)malloc(strlen(name)+1);
    strncpy(res->name, name, strlen(name)+1);
    lvgl_resource_id++;
    res->id = lvgl_resource_id;
    res->room = room;
    res->dsc = (void *)malloc(sizeof(lv_img_dsc_t));
    res->data = (unsigned char *)malloc(room);
    res->size = 0;

    pdsc = (lv_img_dsc_t *)res->dsc;
    *pdsc = dsc;
    pdsc->data = res->data;

    rt_list_insert_after(&lvgl_resource_header, &res->list);

    return lvgl_resource_id;
}

void lvgl_isd_resource_del(const char *name)
{
    LVGLResource *res;

    rt_list_for_each_entry(res, &lvgl_resource_header, list){
        if (strcmp(res->name, name) == 0) {
            free(res->name);
            free(res->data);
            break;
        }
    }
}

void lvgl_isd_resource_build(const char *name, const void *src, int32_t len)
{
    LVGLResource *res;

    rt_list_for_each_entry(res, &lvgl_resource_header, list){
        if (strcmp(res->name, name) == 0) {
            if(res->size + len <= res->room) {
                memcpy(&res->data[res->size], src, len);
                res->size += len;
            }
            break;
        }
    }
}

void *lvgl_isd_resource_dsc(const char *name)
{
    LVGLResource *res;

    rt_list_for_each_entry(res, &lvgl_resource_header, list){
        if (strcmp(res->name, name) == 0) {
            return (void *)res->dsc;
        }
    }
    return NULL;
}

uint32_t lvgl_isd_resource_check(const char *name)
{
// TODO: crc32 check
    uint32_t crc32 = 0xFFFFFFFF;

    return crc32;
}
